import { createApp } from 'vue'
// import 'lib-flexible'
import './utils/flexble'
import './styles/reset.css'
import App from './App.vue'
import router from './router/index'
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//store的使用方式
import { menuStore } from '@/store/menu'
import { userStore } from '@/store/user'
const app = createApp(App)
const pinia = createPinia().use(piniaPluginPersist)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component) //注册所有图标
}

app.use(router).use(pinia).mount('#app')

//权限验证处理:全集守卫路由实现
const whiteList = ['/login'] //白名单
router.beforeEach(async (to, from, next) => {
  const ustore = userStore()
  const mstore = menuStore()
  //获取token
  const token = ustore.$state.token
  if (token) {
    if (to.path === '/login' || to.path === '/') {
      next({ path: '/' }) //直接跳到首页
    } else {
      //从vuex里面获取菜单并且有权限
      const hasRoles = ustore.permissions && ustore.permissions.length > 0
      if (hasRoles) {
        // 如果有权限
        next()
      } else {
        try {
          //vuex中不存在权限，从服务器获取
          await ustore.getInfo()
          //获取菜单、动态生成路由
          await mstore.getMenuList(router)
          //确保动态添加的路由已经被完全加载上去
          next({ ...to, replace: true })
        } catch (error) {
          //重置token
          ustore.$reset()
          //跳到登录
          next({ path: '/login' })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      //如果在白名单中继续访问当前路由
      next()
    } else {
      next({ path: '/login' })
    }
  }
})
